package com.szcinda.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.repository.Consolidate;
import com.szcinda.service.PageResult;
import com.szcinda.service.dto.consolidate.ConsolidateExcelListener;
import com.szcinda.service.dto.consolidate.ConsolidateImportDto;
import com.szcinda.service.dto.consolidate.ConsolidateQueryDto;
import com.szcinda.service.dto.consolidate.ConsolidateService;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("consolidate")
public class ConsolidateController {

    private final ConsolidateService consolidateService;

    public ConsolidateController(ConsolidateService consolidateService) {
        this.consolidateService = consolidateService;
    }

    @PostMapping("/import")
    @OperationLogAnnotation(operDesc = "导入拼箱订单", operModel = "拼箱订单")
    public Result<?> orderImport(@RequestParam("file") MultipartFile file) throws Exception {
        // 解析每行结果在listener中处理
        InputStream inputStream = file.getInputStream();
        try {
            ConsolidateExcelListener listener = new ConsolidateExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 2, ConsolidateImportDto.class), listener);
            return Result.success(consolidateService.importData(listener.getImportDatas()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @PostMapping("exportBySelect")
    @OperationLogAnnotation(operDesc = "导出拼箱订单", operModel = "拼箱订单")
    public void exportBySelect(@RequestParam String ids, HttpServletResponse response) throws Exception {
        List<Consolidate> list = consolidateService.queryByIds(Arrays.asList(ids.split(",")));
        int index = 1;
        for (Consolidate consolidate : list) {
            consolidate.setIndex(index);
            index++;
        }
        Map<String, Object> beans = new HashMap<>();
        beans.put("list", list);
        InputStream is = null;
        OutputStream os = response.getOutputStream();
        // 下载EXCEL
        String fName = URLEncoder.encode("拼箱导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fName + ".xlsx");
        try {
            // 获取模板文件
            is = this.getClass().getClassLoader().getResourceAsStream("templates//拼箱导出模板.xlsx");
            // 实例化 XLSTransformer 对象
            XLSTransformer xlsTransformer = new XLSTransformer();
            // 获取 Workbook ，传入 模板 和 数据
            Workbook workbook = xlsTransformer.transformXLS(is, beans);
            // 输出
            workbook.write(os);
            os.flush();
            // 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
        } catch (Exception ignored) {

        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    @PostMapping("export")
    @OperationLogAnnotation(operDesc = "导出拼箱订单", operModel = "拼箱订单")
    public void export(@RequestParam(required = false) String createTimeStart, @RequestParam(required = false) String createTimeEnd,
                       @RequestParam(required = false) String pNo, @RequestParam(required = false) String jcNo,
                       @RequestParam(required = false) String packageNo, @RequestParam(required = false) String packageTime,
                       @RequestParam(required = false) String belong, @RequestParam(required = false) String line,
                       HttpServletResponse response) throws Exception {
        ConsolidateQueryDto params = new ConsolidateQueryDto();
        if (StringUtils.hasText(createTimeStart)) {
            params.setCreateTimeStart(LocalDate.parse(createTimeStart, dateTimeFormatter));
        } else {
            // 如果不选，则只查一天数据
            params.setCreateTimeStart(LocalDate.now());
        }
        if (StringUtils.hasText(createTimeEnd)) {
            params.setCreateTimeEnd(LocalDate.parse(createTimeEnd, dateTimeFormatter));
        } else {
            // 如果不选，则只查一天数据
            params.setCreateTimeEnd(LocalDate.now().plusDays(1));
        }
        params.setPNo(pNo);
        params.setBelong(belong);
        params.setJcNo(jcNo);
        params.setPackageTime(packageTime);
        params.setPackageNo(packageNo);
        params.setLine(line);
        List<Consolidate> list = consolidateService.queryAll(params);
        int index = 1;
        for (Consolidate consolidate : list) {
            consolidate.setIndex(index);
            index++;
        }
        Map<String, Object> beans = new HashMap<>();
        beans.put("list", list);
        InputStream is = null;
        OutputStream os = response.getOutputStream();
        // 下载EXCEL
        String fName = URLEncoder.encode("拼箱导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fName + ".xlsx");
        try {
            // 获取模板文件
            is = this.getClass().getClassLoader().getResourceAsStream("templates//拼箱导出模板.xlsx");
            // 实例化 XLSTransformer 对象
            XLSTransformer xlsTransformer = new XLSTransformer();
            // 获取 Workbook ，传入 模板 和 数据
            Workbook workbook = xlsTransformer.transformXLS(is, beans);
            // 输出
            workbook.write(os);
            os.flush();
            // 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
        } catch (Exception ignored) {

        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    @PostMapping("query")
    public PageResult<Consolidate> query(@RequestBody ConsolidateQueryDto queryDto) {
        return consolidateService.query(queryDto);
    }

    @PostMapping("update")
    @OperationLogAnnotation(operDesc = "修改拼箱订单", operModel = "拼箱订单")
    public Result<?> update(@RequestBody Consolidate consolidate) {
        return consolidateService.update(consolidate);
    }

    @GetMapping("/del/{id}")
    @OperationLogAnnotation(operDesc = "删除拼箱订单", operModel = "拼箱订单")
    public Result<String> delete(@PathVariable String id) {
        consolidateService.delete(id);
        return Result.success();
    }
}
